package com.linxi.handy;

import com.linxi.handy.common.Constants;
import com.linxi.handy.component.control.HomeControl;
import com.linxi.handy.component.dialog.DatabaseDialog;
import com.linxi.handy.component.dialog.ExecMysqlDialog;
import com.linxi.handy.component.view.Tableview;
import com.linxi.handy.entity.User;
import com.linxi.handy.service.CacheService;
import com.linxi.handy.service.impl.UserCacheService;
import com.linxi.handy.util.ConnectionUtils;
import com.linxi.handy.util.LogUtil;
import org.apache.commons.lang.StringUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 登录面板
 *
 * @author mac
 */
public class Application {
    /**
     * 登陆界面要的组件
     */
    public static JFrame login = new JFrame("登录");
    private final BackGroundPanel backGroundPanel = new BackGroundPanel();
    private final JPanel userLine = new JPanel();
    private final JPanel passwdLine = new JPanel();
    private final JPanel addressLine = new JPanel();
    private final JPanel loginLine = new JPanel();
    private final JLabel nameLabel = new JLabel("用  户");
    private final JLabel passwordLabel = new JLabel("密  码");
    private final JLabel addressLabel = new JLabel("地  址");
    private final JTextField usernameText = new JTextField(12);
    private final JPasswordField passwordText = new JPasswordField(12);
    private final JButton enterButton = new JButton("登   录");

    public String url;
    public String name;
    public String password;
    public String host;
    private String lookaround = "javax.swing.plaf.nimbus.NimbusLookAndFeel";
    private String urlTemplate = "jdbc:mysql://%s/?user=%s&password=%s&useSSL=false&useUnicode=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull";

    private CacheService<User> userCacheService = new UserCacheService();

    public static void main(String[] args) {
        new Application();
    }

    public Application() {
        try {
            UIManager.setLookAndFeel(lookaround);
        } catch (Exception e) {
            e.printStackTrace();
        }

        enterButton.addActionListener(new EnterProcessListener());
        userLine.add(nameLabel);
        userLine.add(usernameText);
        passwdLine.add(passwordLabel);
        passwdLine.add(passwordText);
        addressLine.add(addressLabel);
        loginLine.setLayout(null);
        loginLine.add(enterButton);
        enterButton.setBounds(200, 5, 100, 35);

        login.setLayout(null);
        login.add(backGroundPanel);
        login.add(userLine);
        login.add(passwdLine);
        login.add(addressLine);
        login.add(loginLine);
        backGroundPanel.setBounds(0, 0, 500, 160);
        addressLine.setBounds(0, 160, 500, 50);
        userLine.setBounds(0, 210, 500, 50);
        passwdLine.setBounds(0, 260, 500, 50);
        loginLine.setBounds(0, 310, 500, 90);

        //设置一些颜色和其他属性
        User currentUser = userCacheService.getCacheList().get(0);

        usernameText.setText(currentUser.getUser());
        passwordText.setText(currentUser.getPassword());
        JComboBox hostComboBox = initHostCombobox();
        hostComboBox.setBounds(0, 160, 500, 50);
        hostComboBox.setEditable(true);
        hostComboBox.setFont(Constants.DEFAULT_FONT_15);
        addressLine.add(hostComboBox);

        userLine.setBackground(Constants.WRITE_COLOR);
        passwdLine.setBackground(Constants.WRITE_COLOR);
        addressLine.setBackground(Constants.WRITE_COLOR);
        loginLine.setBackground(Constants.WRITE_COLOR);
        nameLabel.setFont(Constants.DEFAULT_FONT_15);
        passwordLabel.setFont(Constants.DEFAULT_FONT_15);
        addressLabel.setFont(Constants.DEFAULT_FONT_15);
        usernameText.setFont(Constants.DEFAULT_FONT_15);
        passwordText.setFont(Constants.DEFAULT_FONT_15);
        enterButton.setFont(Constants.DEFAULT_FONT_16);
        enterButton.setBackground(Color.WHITE);

        Image image = new ImageIcon(getClass().getResource(Constants.LOGO)).getImage();
        login.setIconImage(image);

        login.setResizable(false);
        login.setSize(500, 400);
        //将窗体设置在屏幕中间
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        Dimension size = login.getSize();
        int x = (screenSize.width - size.width) / 2;
        int y = (screenSize.height - size.height) / 2;
        login.setLocation(x, y);
        login.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        login.setVisible(true);
        usernameText.requestFocus();
    }

    public JComboBox initHostCombobox() {
        List<String> hosts = userCacheService.getCacheList().stream().map(item -> item.getHost()).collect(Collectors.toList());
        JComboBox hostComboBox = new JComboBox(hosts.toArray());
        hostComboBox.addItemListener(e -> {
            // 这个item发生改变的会触发两次，一次是当前item的，第二次是改变后的item
            // 1.将当次item的 改变进行记录
            // 2.展示第二次出来的时候把item的user、password下拉出来
            LogUtil.log(e.toString());
            if (e.getStateChange() == 1 || StringUtils.isBlank((String) e.getItem())) {
                return;
            }
            userCacheService.selectiveUpdateCache(new User((String) e.getItem(), usernameText.getText(), String.valueOf(passwordText.getPassword())));
        });
        return hostComboBox;
    }

    public void setConnection() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            LogUtil.log("成功加载Mysql驱动程序");
            Tableview.conn = ConnectionUtils.getConnection(url);
            DatabaseDialog.conn = ConnectionUtils.getConnection(url);
            ExecMysqlDialog.conn = ConnectionUtils.getConnection(url);
        } catch (ClassNotFoundException e1) {
            System.out.println("找不到Mysql驱动程序");
            e1.printStackTrace();
        } catch (SQLException e1) {
            e1.printStackTrace();
        }
    }

    class EnterProcessListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            enterButton.setText("连接中...");
            name = usernameText.getText();
            password = new String(passwordText.getPassword());
            host = (String) ((JComboBox) addressLine.getComponent(1)).getSelectedItem();
            url = String.format(urlTemplate, host, name, password);
            setConnection();
            if (ConnectionUtils.isConnect()) {
                new HomeControl();
                enterButton.setText("登   录");
                userCacheService.selectiveUpdateCache(new User(host, name, password));
            } else {
                JOptionPane.showMessageDialog(login, "用户名或密码错误", "登录失败", JOptionPane.CLOSED_OPTION);
                enterButton.setText("登   录");
            }
        }
    }

    /**
     * 带背景的JPanel
     */
    class BackGroundPanel extends JPanel {

        Image image;

        BackGroundPanel() {
            image = new ImageIcon(getClass().getResource(Constants.MAIN)).getImage();
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            image.getWidth(this);
            image.getHeight(this);
            //绘制图片
            g.drawImage(image, 0, 0, null);
        }
    }
}
